package com.lzy.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lzy.common.QueryPageParam;
import com.lzy.entity.Result;
import com.lzy.entity.Student;
import com.lzy.service.IStudentService;

import com.lzy.vo.StudentWithClassVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2025-04-25
 */
@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private IStudentService studentService;

    //日志对象
    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(StudentController.class);


    @GetMapping("/list")
    public Result list() {
        List<Student> list = studentService.getAll();
        log.info("查询结果：{}", list);
        return Result.success(list);
    }

    //分页查询
    @PostMapping("/listPage")
    public Result listPage(@RequestBody QueryPageParam query) {
        log.info("分页查询参数：{}", query);
        Page<StudentWithClassVO> page = new Page<>(query.getPageNum(), query.getPageSize());
        IPage result = studentService.getPage(page, query.getParam());
        return Result.success(result.getRecords(), result.getTotal());
    }

    //新增学生信息
    @PostMapping("/create")
    public Result create(@RequestBody Student student) {
        log.info("新增学生信息：{}", student);
        return studentService.createStudent(student) ? Result.success() : Result.fail();
    }

    //更新学生信息
    @PostMapping("/update")
    public Result update(@RequestBody Student student) {
        log.info("更新学生信息：{}", student);
        return studentService.updateStudent(student) ? Result.success() : Result.fail();
    }

    //删除学生信息
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") Integer id) {
        log.info("删除学生信息：{}", id);
        return studentService.delStudent(id) ? Result.success() : Result.fail();
    }

    @GetMapping("/checkStuNo")
    public Result checkStuNoExists(@RequestParam String stuNo) {
        log.info("---------------------------------------------");
        log.info("检查学生学号唯一性");
        // 根据学号查询学生
        LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Student::getStuNo, stuNo);
        Student student = studentService.getOne(queryWrapper);
        // 返回学号是否已存在
        return Result.success(student != null);
    }
}
